package com.cardone.platform.usercenter.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.WebUtils;

import com.cardone.context.ContextHolder;
import com.cardone.context.Contexts;
import com.cardone.platform.configuration.dto.SiteDto;
import com.cardone.platform.configuration.util.SiteUtils;
import com.cardone.platform.usercenter.dto.UserDto;
import com.cardone.platform.usercenter.service.UserService;

/**
 * 用户工具类
 *
 * @author yaohaitao
 *
 */
@Slf4j
public class UserUtils {
	/**
	 * 默认用户
	 */
	@Setter
	private static UserDto defaultUser;

	/**
	 * 查询：登录用户
	 *
	 * @return 登录用户
	 */
	public static UserDto findForLogin() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return UserUtils.findForLogin(request);
	}

	/**
	 * 初始化
	 */
	public static void initForLogin() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		UserUtils.initForLogin(request);
	}

	/**
	 * 初始化
	 * 
	 * @param request
	 */
	public static void initForLogin(final HttpServletRequest request) {
		final String loginKey = UserUtils.readLoginKey(request);

		if (StringUtils.isBlank(loginKey)) {
			return;
		}

		final SiteDto contextSite = SiteUtils.getContextSite();

		UserDto loginUser = null;

		final UserDto findUser = UserDto.newUser();

		findUser.setSiteId(contextSite.getId());

		findUser.setLoginKey(loginKey);

		findUser.setLoadPermissionList(true);

		try {
			loginUser = ContextHolder.getBean(UserService.class).findById(findUser);
		} catch (final Exception e) {
			UserUtils.log.error(e.getMessage(), e);
		}

		if (loginUser == null) {
			return;
		}

		loginUser.setSiteId(contextSite.getId());

		loginUser.setLoginKey(loginKey);

		request.setAttribute(Contexts.loginUser.name(), loginUser);

		WebUtils.setSessionAttribute(request, Contexts.loginUser.name(), loginUser);
	}

	/**
	 * 查询：登录用户
	 *
	 * @param request
	 *          HttpServletRequest
	 * @return 登录用户
	 */
	public static UserDto findForLogin(final HttpServletRequest request) {
		UserDto loginUser = (UserDto) request.getAttribute(Contexts.loginUser.name());

		if ((loginUser != null) && StringUtils.isNotBlank(loginUser.getId())) {
			return loginUser;
		}

		loginUser = (UserDto) WebUtils.getSessionAttribute(request, Contexts.loginUser.name());

		if ((loginUser != null) && StringUtils.isNotBlank(loginUser.getId())) {
			request.setAttribute(Contexts.loginUser.name(), loginUser);

			return loginUser;
		}

		do {
			final String loginKey = UserUtils.readLoginKey(request);

			final SiteDto contextSite = SiteUtils.getContextSite();

			if (StringUtils.isNotBlank(loginKey)) {
				final UserDto findUser = UserDto.newUser();

				findUser.setSiteId(contextSite.getId());

				findUser.setLoginKey(loginKey);

				findUser.setLoadPermissionList(true);

				try {
					loginUser = ContextHolder.getBean(UserService.class).findById(findUser);
				} catch (final Exception e) {
					UserUtils.log.error(e.getMessage(), e);
				}

				if (loginUser != null) {
					loginUser.setSiteId(contextSite.getId());

					loginUser.setLoginKey(loginKey);

					break;
				}
			}

			loginUser = UserDto.newUser();

			if (UserUtils.defaultUser != null) {
				BeanUtils.copyProperties(UserUtils.defaultUser, loginUser);
			}

			loginUser.setSiteId(contextSite.getId());
		} while (false);

		request.setAttribute(Contexts.loginUser.name(), loginUser);

		WebUtils.setSessionAttribute(request, Contexts.loginUser.name(), loginUser);

		return loginUser;
	}

	/**
	 * 是否移动设备
	 *
	 * @return 是否移动设备
	 */
	public static boolean isMobileDevices() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return UserUtils.isMobileDevices(request);
	}

	/**
	 * 是否移动设备
	 *
	 * @param request
	 * @return 是否移动设备
	 */
	public static boolean isMobileDevices(final HttpServletRequest request) {
		final String userAgent = request.getHeader("User-Agent");

		if (StringUtils.containsIgnoreCase(userAgent, "android")) {
			return true;
		}

		if (StringUtils.containsIgnoreCase(userAgent, "ios")) {
			return true;
		}

		Device currentDevice = DeviceUtils.getCurrentDevice(request);

		if (currentDevice != null) {
			return currentDevice.isMobile();
		}

		return false;
	}

	/**
	 * 登录
	 *
	 * @param request
	 *          HttpServletRequest
	 * @param loginUser
	 *          登录信息
	 * @return 登录结果
	 */
	public static UserDto login(final HttpServletRequest request, final UserDto loginUser) {
		final SiteDto contextSite = SiteUtils.getContextSite();

		loginUser.setSiteId(contextSite.getId());

		final UserDto user = ContextHolder.getBean(UserService.class).login(loginUser);

		if (user == null) {
			return user;
		}

		UserUtils.setLoginKey(request, user.getLoginKey());

		request.setAttribute(Contexts.loginUser.name(), loginUser);

		WebUtils.setSessionAttribute(request, Contexts.loginUser.name(), loginUser);

		return user;
	}

	/**
	 * 登录
	 *
	 * @param loginUser
	 *          登录信息
	 * @return 登录结果
	 */
	public static UserDto login(final UserDto loginUser) {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return UserUtils.login(request, loginUser);
	}

	/**
	 * 注销
	 *
	 */
	public static void logout() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		UserUtils.logout(request);
	}

	/**
	 * 注销
	 *
	 * @param request
	 *          HttpServletRequest
	 */
	public static void logout(final HttpServletRequest request) {
		request.getSession().invalidate();
	}

	/**
	 * 读取用户标识
	 *
	 * @return 用户标识
	 */
	public static String readIdForLogin() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return UserUtils.readIdForLogin(request);
	}

	/**
	 * 读取用户标识
	 *
	 * @param request
	 *          HttpServletRequest
	 * @return 用户标识
	 */
	public static String readIdForLogin(final HttpServletRequest request) {
		return UserUtils.findForLogin(request).getId();
	}

	/**
	 * 读取login标识
	 *
	 * @return login标识
	 */
	public static String readLoginKey() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return UserUtils.readLoginKey(request);
	}

	/**
	 * 读取login标识
	 *
	 * @param request
	 *          HttpServletRequest
	 * @return login标识
	 */
	public static String readLoginKey(final HttpServletRequest request) {
		String loginKey = (String) request.getAttribute(Contexts.loginKey.stringValue());

		if (StringUtils.isNotBlank(loginKey)) {
			return loginKey;
		}

		loginKey = (String) WebUtils.getSessionAttribute(request, Contexts.loginKey.stringValue());

		if (StringUtils.isNotBlank(loginKey)) {
			request.setAttribute(Contexts.loginKey.stringValue(), loginKey);

			return loginKey;
		}

		do {
			loginKey = request.getHeader(Contexts.loginKey.stringValue());

			if (StringUtils.isNotBlank(loginKey)) {
				break;
			}

			if (UserUtils.isMobileDevices(request)) {
				loginKey = request.getParameter(Contexts.loginKey.stringValue());

				if (StringUtils.isNotBlank(loginKey)) {
					break;
				}
			}

			final Cookie cookie = WebUtils.getCookie(request, Contexts.loginKey.stringValue());

			if (cookie != null) {
				loginKey = cookie.getValue();
			}
		} while (false);

		UserUtils.setLoginKey(request, loginKey);

		return loginKey;
	}

	/**
	 * 登录
	 *
	 * @param request
	 *          HttpServletRequest
	 * @param loginUser
	 *          登录信息
	 * @return 登录结果
	 */
	public static UserDto register(final HttpServletRequest request, final UserDto registerUser) {
		final UserDto user = ContextHolder.getBean(UserService.class).register(registerUser);

		if (user == null) {
			return user;
		}

		UserUtils.setLoginKey(request, user.getLoginKey());

		WebUtils.setSessionAttribute(request, Contexts.loginUser.name(), user);

		return user;
	}

	/**
	 * 登录
	 *
	 * @param loginUser
	 *          登录信息
	 * @return 登录结果
	 */
	public static UserDto register(final UserDto registerUser) {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return UserUtils.register(request, registerUser);
	}

	/**
	 * 设置登录key
	 *
	 * @param request
	 *          HttpServletRequest
	 * @param loginKey
	 *          登录key
	 */
	public static void setLoginKey(final HttpServletRequest request, final String loginKey) {
		request.setAttribute(Contexts.loginKey.stringValue(), loginKey);

		WebUtils.setSessionAttribute(request, Contexts.loginKey.stringValue(), loginKey);
	}

	/**
	 * 设置登录key
	 *
	 * @param loginKey
	 *          登录key
	 */
	public static void setLoginKey(final String loginKey) {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		UserUtils.setLoginKey(request, loginKey);
	}
}
